package com.netMgr.webServer{
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.SecurityErrorEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.net.URLRequestHeader;
	import flash.net.URLRequestMethod;
	import flash.net.URLVariables;

	public class HttpRequest{
		private var urlLoader:URLLoader = new URLLoader();
		private var vo:HttpRequestVo;
		public function HttpRequest()
		{
		}
		/**
		 *WEB数据请求 
		 * @param vo 参数结构
		 * 
		 */	
		static public function request(v:HttpRequestVo):void{
			if(!checkUrl(v.url))return;
			var ws:HttpRequest=new HttpRequest();
			ws.load(v);
		}
		static private function checkUrl(url:String):Boolean{
			if(url.length<4){
				trace("请求地址太短，抛弃~~");
				return false;
			}
			return true;
		}
		/**请求数据 相关参数详见HttpRequestVo.as**/
		public function load(data:HttpRequestVo):void{
			vo=data;
			var urlRequest:URLRequest = new URLRequest(vo.url); //接收数据。
			if(vo.header)setHeaders(urlRequest,vo.header);
			if(vo.param){
				urlRequest.method = (vo.type?vo.type:URLRequestMethod.POST);
				if(vo.format==1){
					urlRequest.data=JSON.stringify(vo.param);
					urlRequest.contentType="application/json";
				}else if(vo.format==3){
					vo.url+="?";
					for(var i:String in vo.param)vo.url+="&&"+i+"="+vo.param[i];
				}else{
					var urlVariables:URLVariables = new URLVariables();
					for(var i:String in vo.param)urlVariables[i]=(vo.param[i] is String?vo.param[i]:JSON.stringify(vo.param[i]));
					urlRequest.data = urlVariables;
				}
			}
			trace("addLoader:-->"+vo.url+"      param："+JSON.stringify(vo.param));
			urlLoader.load(urlRequest);
			urlLoader.addEventListener(Event.COMPLETE, complete);
			urlLoader.addEventListener(SecurityErrorEvent.SECURITY_ERROR,safeError);
			urlLoader.addEventListener(IOErrorEvent.IO_ERROR,loadError);
		}
		/**设置头部信息**/
		private function setHeaders(request:URLRequest,param:Object):void{
			for(var key:String in param){
				var head:URLRequestHeader = new URLRequestHeader(key,param[key]);
				request.requestHeaders.push(head);
			}
		}
		/**请求异常**/
		private function loadError(e:IOErrorEvent):void{
			trace("urlLoaderError: --> "+e.text);
			if(vo.onError)vo.onError(e.text);
		}
		/**请求完成**/
		private function complete(e:Event):void{
			trace("urlLoaderData:-->"+unescape(e.target.data));
			var obj:Object=JSON.parse(unescape(e.target.data));
			if(vo.onComplete)vo.onComplete(obj);
		}
		/**安全沙箱错误**/
		private function safeError(e:SecurityErrorEvent):void{
			trace("urlLoaderSafeError: --> "+e.text);
		}
	}
}